﻿@{
    ViewBag.Title = "添加采购入库单据";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>采购入库单添加</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 10px;
        }

        .layui-column {
            display: flex;
            flex: 1;
            flex-direction: column;
            margin-right: 10px;
        }
        /* 表单行样式 */
        .layui-inline {
            display: flex;
            flex-direction: row;
            margin-bottom: 10px;
        }

        input, select {
            width: 160px; /* 调整输入框和选择框宽度 */
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 10px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn" id="saveButton">保存</button>
            @* <button class="layui-btn layui-btn-primary" id="cancelButton">取消</button> *@
            @*  <button class="layui-btn layui-btn-normal" id="approveButton">审核</button>
            <button class="layui-btn layui-btn-disabled" id="reapproveButton">反审核</button> *@
            @* <button class="layui-btn layui-btn-mini" id="collapseButton">收起</button> *@
        </div>
        <!-- 表单信息 -->
        <div style="display:flex;flex-wrap:wrap;width:100%;">
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据编码:</label>
                    <input type="text" id="id" class="layui-input-inline" disabled>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务类型:</label>
                    <div class="layui-input-inline">
                        <select id="businessType">
                            <option value="1">销售订单</option>
                            <option value="2" selected>采购入库</option>
                            <option value="3">销售出库</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">期间:</label>
                    <input type="date" id="qiJianDate" class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">操作员:</label>
                    <input type="text" id="oprator" class="layui-input-inline">
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据日期:</label>
                    <input type="date" id="documentDate"  class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务状态:</label>
                    <div class="layui-input-inline">
                        <select id="businessStatus">
                            <option value="1">正常</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">仓库:</label>
                    <select id="repository">
                        <option value="1">原材料仓库</option>
                        <option value="2">在制品仓库</option>
                        <option value="3">成品仓库</option>
                        <option value="4">保税仓库</option>
                        <option value="5">危险品仓库</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">供方</label>
                    <input type="text" id="supplyUser" class="layui-input-inline" />
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">审核日期:</label>
                    <input type="date" id="examDate"  class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务部门:</label>
                    <div class="layui-input-inline">
                        <select id="businessDempt">
                            <option value="1">战略咨询部门</option>
                            <option value="2">财务咨询部门</option>
                            <option value="3">财务营销部门</option>
                            <option value="4">IT信息技术部门</option>
                            <option value="5">人力资源部门</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">到货单号:</label>
                    <input type="text" id="arivalNumber" class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">备注信息:</label>
                    <input type="text" id="remark" class="layui-input-inline">
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据类型:</label>
                    <select id="documentType" class="layui-input-inline">
                            <option value="1">销售订单</option>
                        <option value="2" selected>采购入库单</option>
                            <option value="3">销售出库单</option>
                        </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">单据状态:</label>
                    <select id="documentStatus" class="layui-input-inline">
                        <option value="0">开立</option>
                        <option value="1">退回</option>
                        <option value="2">审核</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务人员:</label>
                    <input type="text" id="businessUser" class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">审批人:</label>
                    <select id="examUserName">
                        
                    </select>
                </div>
            </div>
        </div><br />
        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            @* <button class="layui-btn layui-btn-xs" id="importButton">引入</button> *@
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
        </div>

        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>主计量</th>
                    <th>出库数量</th>
                    <th>批号</th>
                    <th>质量要求</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
   @*  //在html代码中添加一个隐藏的模版，用于展示物料清单表格 *@
    <script type="text/html" id="materialListTemplate">
        <div style="padding: 10px;">
            <table class="layui-table" id="materialListTable">
                <thead>
                    <tr>
                        <th>物料编码</th>
                        <th>物料名称</th>
                        <th>型号规格</th>
                        <th>主计量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </script>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;
            var CurrentRowIndex;
            // 初始化一个空行
            function initEmptyRow() {
                return {
                    materialsCode: 0,
                    materialsName: '',
                    modelSpecification: '',
                    calulate: '',
                    outBoundNumber: 0,
                    batch: '',
                    qualityRequir: '',
                    remark: '',
                    materialsClass: 2
                };
            }
            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml = `
                                         <tr data-index="${rowCount - 1}">
                                                                    <td>${rowCount}</td>
                                                                    <td>
                                                                                <input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="物料编码" readonly>
                                                                                <button type="button" class="layui-btn layui-btn-xs selectMaterialButton" data-rowIndex="' + rowIndex + '">选择</button>
                                                                    </td>
                                                                            <td><input type="text" class="layui-input materialsName" value="${material.materialsName}" id="materialsName" placeholder="物料名称" readonly></td>
                                                                                            <td><input type="text" class="layui-input" value="${material.modelSpecification}" id="modelSpecification" placeholder="型号规格"></td>
                                                                    <td>
                                                                                <select class="layui-select calulate" id="calulate">
                                                                            <option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option>
                                                                            <option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option>
                                                                            <option value="张" ${material.calulate === '张' ? 'selected' : ''}>张</option>
                                                                            <option value="千克" ${material.calulate === '千克' ? 'selected' : ''}>千克</option>
                                                                            <option value="克" ${material.calulate === '克' ? 'selected' : ''}>克</option>
                                                                            </select>
                                                                    </td>
                                                                            <td><input type="number" class="layui-input outBoundNumber" id="outBoundNumber" value="${material.outBoundNumber}" placeholder="出库数量"></td>
                                                                            <td><input type="text" class="layui-input batch" id="batch" value="${material.batch}" placeholder="批号"></td>
                                                                            <td><input type="text" class="layui-input qualityRequir" id="qualityRequir" value="${material.qualityRequir}" placeholder="质量要求"></td>
                                                                            <td><input type="text" class="layui-input remark" id="remark" value="${material.remark}" placeholder="备注"></td>
                                                                    <td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button></td>
                                                                </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }

            // 初始化一个空行
            addMaterialRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });
            //物料弹出框
            function showMaterialList() {
                layer.open({
                    type: 1,
                    title: '选择物料',
                    area: ['800px', '500px'],
                    content: $('#materialListTemplate').html(), // 假设后面会创建一个物料清单模板
                    success: function (layero) {
                        // 调用接口获取物料数据
                        $.ajax({
                            url: 'http://localhost:5234/api/Materials/GetMaterial_Basic',
                            //url: "@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic",
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 0) {
                                    var materialList = res.data;
                                    var tableBody = $('#materialListTable tbody');
                                    tableBody.empty();
                                    materialList.forEach(function (material) {
                                        var row = $('<tr>'); 
                                        row.append($('<td>').text(material.material_code));
                                        row.append($('<td>').text(material.material_name));
                                        row.append($('<td>').text(material.model_specification));
                                        row.append($('<td>').text(material.unit_of_measurement_name));
                                        row.append($('<td>').html('<button class="layui-btn layui-btn-xs selectMaterialConfirm">确认</button>'));
                                        row.data('material', material);
                                        tableBody.append(row);
                                    });
                                    form.render();
                                } else {
                                    layer.msg(res.msg || '获取物料数据失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('请求失败: ' + error, { icon: 2 });
                                console.error(xhr.responseText);
                            }
                        });
                    }
                });
            }
            $(function () {
                // 获取审批人数据并填充下拉框
                $.ajax({
                    url: 'https://localhost:7174/api/Message/GetUser',
                    //url: "@ViewBag.BaseUrl/T5/Message/GetUser",
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 210) {
                            var users = res.data;
                            var options = '';
                            users.forEach(function (user) {
                                options += `<option value="${user.userName}">${user.userName}</option>`;
                            });
                            $('#examUserName').html(options);
                            form.render('select');
                        } else {
                            layer.msg(res.msg || '获取用户数据失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            })
            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', {
                    btn: ['确定', '取消'] // 按钮文本
                }, function (index) { // 点击确定后的回调
                    $tr.remove();
                    // 重新编号
                    $('#materialTable tbody tr').each(function (index) {
                        $(this).find('td:first').text(index + 1);
                    });
                    layer.close(index); // 关键：关闭当前弹窗
                }, function (index) {
                    layer.close(index); // 取消时也关闭弹窗
                });
            });
            //选择按钮绑定点击事件
            $(document).on('click', '.selectMaterialButton', function () {
                var $this = $(this);
                var rowIndex = $this.closest('tr').data('index');//获取当前行的索引
                CurrentRowIndex = rowIndex;
                console.log("获取当前行的索引", CurrentRowIndex);
                showMaterialList();
            });
            //处理"确定选择"按钮后的回填操作
            $(document).on('click', '.selectMaterialConfirm', function () {
                var material = $(this).closest('tr').data('material');
                var currentRow = $('#materialTable tbody tr').eq(CurrentRowIndex); // 获取当前选中的表格行
                currentRow.find('#materialsCode').val(material.material_code);
                currentRow.find('#materialsName').val(material.material_name);
                currentRow.find('#modelSpecification').val(material.model_specification);
                var unit = material.unit_of_measurement_name;
                currentRow.find('#calulate option').each(function () {
                    if ($(this).text() === unit) {
                        $(this).prop('selected', true);
                        
                    }
                });
                form.render();
                layer.closeAll('page'); // 关闭物料清单弹窗
            });
            // 保存按钮点击事件
            $('#saveButton').click(function () {
                var formData = {
                    id: $('#documentCode').val() || generateUUID(),
                    businessType: $('#businessType').val() || 2,
                    businessStatus: 1, // 默认状态
                    documentType: 2, // 单据类型
                    documentStatus: 0, // 单据状态
                    oprator: $('#oprator').val(),
                    repository: $('#repository').val(),
                    documentDate: $('#documentDate').val(),
                    supplyUser: $('#supplyUser').val(),
                    businessDemptName:"解决方案一部",
                    businessDempt: $('#businessDempt').val(),
                    businessUser: $('#businessUser').val(),
                    arivalNumber: $('#arivalNumber').val(),
                    remark: $('#remark').val(),
                    qiJianDate: $('#qiJianDate').val(),
                    examDate: $('#examDate').val(),
                    examUserName: $('#examUserName').val(),
                    orderMaterials: []
                };

                // 收集物料数据
                $('#materialTable tbody tr').each(function () {
                    var $tr = $(this);
                    var material = {
                        materialsCode: $tr.find('#materialsCode').val(),
                        materialsName: $tr.find('#materialsName').val(),
                        modelSpecification: $tr.find('#modelSpecification').val(),
                        calulate: $tr.find('#calulate').val(),
                        outBoundNumber: parseFloat($tr.find('#outBoundNumber').val()),
                        batch: '', // 可根据需要填写
                        qualityRequir: $tr.find('#qualityRequir').val(),
                        remark: $tr.find('#remark').val(),
                        materialsClass: 2 // 默认分类
                    };
                    formData.orderMaterials.push(material);
                });

                // 验证必填字段
                if (!formData.examUserName) {
                    layer.msg('请选择审批人', { icon: 2 });
                    return;
                }

                if (formData.orderMaterials.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }
                var loadIndex = layer.load(2);
                console.log("查看添加参数", formData);
                $.ajax({
                    url: 'http://localhost:5090/api/PurchaseInRepository/AddPurchaseInStore',
                    //url: "@ViewBag.BaseUrl/T8/PurchaseInRepository/AddPurchaseInStore",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 212) {
                            layer.msg(res.msg, { icon: 7 }, function () {
                                // 保存成功后可以跳转或刷新页面
                                $('#documentCode').val(formData.id);
                                location.href = "/PurchaseInRepository/GetPurchaseInStore"
                            });
                        } else {
                            layer.msg(res.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            });
            // 生成UUID
            function generateUUID() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c === 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }
        
        
        });
    </script>
</body>
</html>